import api from "../../api/label.js";
// const animation = wx.createAnimation({});
let timer = null
let batchno = null
Page({
  data: {
    canScan: false,
    showScanTips: false,
    isCallPhone: false,
    scanResult: [], // 处理问题 3
    scanNumber: 0,
    scanSuccess: 0,
    labelCodes: [],
    token: wx.getStorageSync('accessToken')
  },
  onLoad: function (query) {
    console.log('微信扫一扫进来的：', query, query.code, query)
    if (query.code) {
      this.checkCode(query.code)
    } else {
      this.onScanCode()
    }
  },
  onScanCode() {
    const that = this
    wx.scanCode({
      success(res) {
        console.log('wx.scanCode：', res.result)
        const code = that.getSearchParams(res.path || res.result).code
        that.checkCode(code)
      },
      complete() {}
    })
  },
  getSearchParams(url) {
    const searchIndex = url?.indexOf('?')
    const searchParamsArray = url?.slice(searchIndex + 1).split('&')
    return searchParamsArray?.reduce((pre, cur) => {
      const [key, value] = cur?.split('=')
      return {
        ...pre,
        [key]: decodeURIComponent(value),
      }
    }, {})
  },
  async checkCode(code) {
    if (code) {
      if (!batchno) {
        const batchnoRes = await api.getBatchno()
        batchno = batchnoRes.data
      }
      try {
        const res = await api.check({
          labelCode: code,
          batchno: batchno
        })
        if (res.code == 1002000009) {
          this.setData({
            isCallPhone: true,
          })
        } else {
          this.setData({
            isCallPhone: false,
            scanResult: res.msg,
            scanSuccess: res.data,
          })
          const resCodeList = this.data.labelCodes
          if (res.data) {
            resCodeList.push(code)
            this.setData({
              canScan: false,
              labelCodes: resCodeList,
            });
            this.onAgainScanCode()
          }
        }
      } catch (error) {
        console.log('checkCode catch：', error)
        if (error.code == 1002000009) {
          this.setData({
            isCallPhone: true,
            canScan: false,
          })
        }
      }
      this.setData({
        scanNumber: this.data.scanNumber + 1,
      });
    }
  },
  onAgainScanCode() {
    this.setData({
      showScanTips: false,
    });
    clearTimeout(timer)
    timer = setTimeout(() => {
      this.onScanCode()
    }, 1000);
  },
  cancelStatus() {
    if (batchno && this.data.scanSuccess) {
      // const app = getApp();
      // app.globalData.labelCodes = this.data.labelCodes;
      wx.reLaunch({
        url: '/pages/scanLog/index?batchno=' + batchno,
      })
    }
    batchno = null
  },
  onMakePhoneCall() {
    wx.makePhoneCall({
      phoneNumber: '13610119338' //仅为示例，并非真实的电话号码
    })
  },
  onUnload() {
    this.cancelStatus()
  }
})